package com.zhiqianbao.activity;

import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.zhiqianbao.utils.Digests;
import com.zhiqianbao.R;
import com.zhiqianbao.entity.Result;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.HttpUtils;
import com.zhiqianbao.utils.ValidateUtils;
import com.rengwuxian.materialedittext.MaterialEditText;

import java.util.HashMap;
import java.util.Map;
import cn.trinea.android.common.util.StringUtils;

/**
 * Created by Administrator on 2015/12/16.
 */
public class ForgetPasswrodActivity extends BaseActivity implements View.OnClickListener{
    /**
     * 手机号码
     */
    EditText edittextTelNum;
    /**
     * 短信验证码
     */
    EditText edittextSmsAuthCode;
    /**
     * 身份证号码
     */
    EditText edittextIdCard;
    /**
     * 新密码
     */
    EditText edittextNewPassword;
    /**
     * 获取短信验证码的按钮
     */
    Button buttonObtainSmsAuthCode;
    /**
     * 重置密码确认按钮
     */
    Button buttonResetPassword;

    TimeCount timeCount;
    private String mpssword;
    //图形验证码
    ImageView loginCode;
    MaterialEditText edittextCode;
    private String msm_data1;
    private String SMS_CODE_TOKEN;


    Handler loginCodeHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RESULT_CANCELED :
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case RESULT_OK :
                    Bitmap codeImage = (Bitmap) msg.obj;
                    loginCode.setImageBitmap(codeImage);
                    break;
            }
        }
    };

    /**
     * 发送验证码处理
     */
    Handler sendCodeHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RESULT_CANCELED :
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case RESULT_OK :
                    Result data = (Result) msg.obj;
                    if(data!=null) {
                        if (Constants.DEFAULT_SUCCESS_CODE.equals(data.getCode())) {
                            //60s后重新发送
                            timeCount.start();
                        } else {
                            showShortToast1(data.getMsg());
                            return;
                        }
                    }
                    break;
            }
        }
    };
    Handler smsTokenHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RESULT_CANCELED:
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case RESULT_OK :
                    Result<String> data = (Result<String>) msg.obj;
                    if(data!=null) {
                        if (data.getCode().equals(Constants.DEFAULT_SUCCESS_CODE)) {
                            //最新短信token
                            msm_data1 = data.getData();
                            SMS_CODE_TOKEN = data.getData();
                            //点击短信验证码
                            if (ValidateUtils.isMobile(edittextTelNum.getText().toString().trim())) {
                                Map<String, String> param = new HashMap<>();
                                param.put("phone", edittextTelNum.getText().toString().trim());
                                param.put("token", msm_data1);
                                param.put("uuid", Constants.UUID);
                                param.put("code", edittextCode.getText().toString().trim());
                                new CodeTaskF().execute(param);
                            } else {
                                showShortToast1("请输入正确的电话号码！");
                            }

                            Log.i("SMS_CODE_TOKEN", "SMS_CODE_TOKEN : " + data.getData());
                        } else {
                            showShortToast1(data.getMsg());
                        }
                    }
                    break;

            }
        }
    };
            /**
             * 修改密码处理
             */
    Handler resetPasswordHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RESULT_CANCELED :
                    gitImageCode();
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case RESULT_OK :
                    Result data = (Result) msg.obj;
                    if(data!=null) {
                        if (Constants.DEFAULT_SUCCESS_CODE.equals(data.getCode())) {
                            //修改成功 关闭当前页面
                            ForgetPasswrodActivity.this.finish();
                            showShortToast1(data.getMsg());
                        } else {
                            gitImageCode();
                            showShortToast1(data.getMsg());
                            return;
                        }
                    }
                    else{
                        gitImageCode();
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget_password);
        init();
        initView();
        gitImageCode();
    }

    /**
     *
     */
    private void initView() {
         edittextTelNum=(EditText)findViewById(R.id.edittext_tel_num);
         edittextSmsAuthCode=(EditText)findViewById(R.id.edittext_sms_auth_code);
         edittextIdCard=(EditText)findViewById(R.id.edittext_id_card);
         edittextNewPassword=(EditText)findViewById(R.id.edittext_new_password);
         buttonObtainSmsAuthCode=(Button)findViewById(R.id.button_obtain_sms_auth_code);
         buttonResetPassword=(Button)findViewById(R.id.button_reset_password);
         loginCode=(ImageView)findViewById(R.id.login_code);
         edittextCode=(MaterialEditText)findViewById(R.id.edittext_code);
        timeCount = new TimeCount(60000, 1000);
        buttonObtainSmsAuthCode.setOnClickListener(this);
        buttonResetPassword.setOnClickListener(this);
        loginCode.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(R.id.button_obtain_sms_auth_code==v.getId()) {
            final String phone = edittextTelNum.getText().toString();
            if (!ValidateUtils.isMobile(phone)) {
                showShortToast1("请输入正确的手机号码！");
                return;
            }
            if (TextUtils.isEmpty(edittextCode.getText().toString().trim())) {
                showShortToast1("请输入图片验证码！");
                return;
            }
            getSmsToken();
        }
        else if(R.id.login_code==v.getId()) {
            gitImageCode();
        }
        else if(R.id.button_reset_password==v.getId()){
                final String resetPhone = edittextTelNum.getText().toString();
                final String code = edittextSmsAuthCode.getText().toString();
                final String idcard = edittextIdCard.getText().toString();
                final String password = edittextNewPassword.getText().toString();

                if (!ValidateUtils.isMobile(resetPhone)) {
                    showShortToast1("请输入正确的手机号！");
                    return;
                }
                if (StringUtils.isBlank(code)) {
                    showShortToast1("请输入手机验证码");
                    return;
                }
                if (!StringUtils.isBlank(idcard)) {
                    if (!ValidateUtils.isIDCard(idcard)) {
                        showShortToast1("请输入正确的身份证号");
                        return;
                    }
                }
                if (!ValidateUtils.isPassword(password)) {
                    showShortToast1("请输入6-12位密码");
                    return;
                }
                 mpssword = Digests.md5(password, resetPhone, Digests.HASH_INTERATIONS);
                //调用重置密码接口
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Message message = new Message();
                        Map<String, String> param = new HashMap<>();

                        param.put("phone", resetPhone);
                        param.put("password", mpssword);
                        param.put("idcard", idcard);
                        param.put("code", code);

                        String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/resetNew", param, ForgetPasswrodActivity.this);
                        if (StringUtils.isBlank(result)) {
                            message.what = RESULT_CANCELED;
                        } else {
                            Result data = Result.fromJson(result, HashMap.class);
                            message.obj = data;
                            message.what = RESULT_OK;
                        }
                        resetPasswordHandler.sendMessage(message);

                    }
                }).start();
        }
    }

    private void getSmsToken() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Map<String, String> params = new HashMap<>();
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/basic/getSmsToken", params, ForgetPasswrodActivity.this);
                Message message = new Message();
                if (StringUtils.isBlank(result)){
                    message.what = RESULT_CANCELED;
                } else {
                    message.what = RESULT_OK;
                    Result<String> data = Result.fromJson(result, String.class);
                    message.obj = data;
                }
                smsTokenHandler.sendMessage(message);
            }
        }).start();
    }

    class CodeTaskF extends AsyncTask<Map,Void,Result>{

        @Override
        protected Result doInBackground(Map... params) {
            String  result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/forgetPasswordCode", params[0], ForgetPasswrodActivity.this);
            Result resultObject = gson.fromJson(result, Result.class);
            return resultObject;
        }

        @Override
        protected void onPostExecute(Result result) {
            if (result == null) {
                showShortToast1("连接超时");
                return;
            }
            if(Constants.DEFAULT_SUCCESS_CODE.equals(result.getCode())) {
                timeCount.start();
            } else {
                showShortToast1(result.getMsg());
            }
        }
    }
    private void gitImageCode() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                Bitmap bitmap = HttpUtils.getUrlImage(Constants.API_ROOT + "/basic/code", ForgetPasswrodActivity.this);
                if (null == bitmap) {
                    message.what = RESULT_CANCELED;
                } else {
                    message.what = RESULT_OK;
                    message.obj = bitmap;
                }
                loginCodeHandler.sendMessage(message);
            }
        }).start();
    }

    private class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }
        @Override
        public void onTick(long millisUntilFinished) {
            buttonObtainSmsAuthCode.setClickable(false);
            buttonObtainSmsAuthCode.setText(millisUntilFinished / 1000 + "s后重新获取");
        }
        @Override
        public void onFinish() {
            buttonObtainSmsAuthCode.setText("重新获取");
            buttonObtainSmsAuthCode.setClickable(true);
        }
    }
}
